//
//  HDLoginViewController.swift
//  Excited
//
//  Created by X140Yu on 6/13/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import PKHUD

class HDLoginViewController: UIViewController {
    
    struct Constants {
    }
    
    @IBOutlet weak var capchaTextField: UITextField!
    @IBOutlet weak var capchaButton: UIButton!
    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var loginButton: UIButton!
    let disposBag = DisposeBag()
    class func present() {
        let loginVC = UIStoryboard(name: "HDLoginViewController", bundle: nil).instantiateInitialViewController() as! HDLoginViewController
        let nav = HDNavigationController(rootViewController: loginVC)
        nav.title = "登录"
        UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(nav, animated: true, completion: {
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "登录"
        
        #if DEBUG
            usernameTextField.text = "20135081"
            passwordTextField.text = "147150"
        #endif
        
        loginButton.layer.cornerRadius = 5
        loginButton.backgroundColor = UIColor.redColor()
        
        let usernameValid = usernameTextField.rx_text.map {
            $0.characters.count == 8 || $0.characters.count == 9
            }.shareReplay(1)
        
        let passwordValid = passwordTextField.rx_text.map {
            $0.characters.count > 4
            }.shareReplay(1)
        
        let capchaValid = capchaTextField.rx_text.map {
            $0.characters.count >= 4
            }.shareReplay(1)
        
        let loginValid = Observable.combineLatest(usernameValid, passwordValid, capchaValid) {
            $0 && $1 && $2
            }.shareReplay(1)
        
        
        loginValid.bindTo(loginButton.rx_enabled).addDisposableTo(disposBag)

        // 强行获取一条验证码
        capchaButtonTaped(capchaButton)

        if usernameTextField.text == "" {
            usernameTextField.becomeFirstResponder()
        } else {
            capchaTextField.becomeFirstResponder()
        }
        
        loginButton.rx_tap.subscribeNext { [unowned self] in
            self.view.endEditing(true)
            HUD.show(.LabeledProgress(title: "正在登录", subtitle: nil))
            HDAPIService.sharedInstance.login(self.usernameTextField.text!, password: self.passwordTextField.text!, captcha: self.capchaTextField.text!, completion: { [unowned self] (error) in
                if let _ = error {
                    dispatch_async(dispatch_get_main_queue(), { 

                    self.loginButton.enabled = true
                    self.capchaButtonTaped(self.capchaButton)
                    self.capchaTextField.becomeFirstResponder()
                    HUD.hide()
                    HUD.flash(.LabeledError(title: "登录失败", subtitle: "请稍后再试"), delay: HUDShowRelay)
                    self.capchaButton.enabled = true
                    })
                    return;
                } else {
                    dispatch_async(dispatch_get_main_queue(), {
                        self.dismissViewControllerAnimated(true) {
                            HUD.hide()
                            HUD.flash(.LabeledSuccess(title: "登录成功~", subtitle: nil), delay: HUDShowRelay)
                            NSNotificationCenter.defaultCenter().postNotificationName(HDUserDidLoginNotificationKey, object: nil)
                        }
                    })
                }
                })
            }.addDisposableTo(disposBag)
    }
    
    @IBAction func capchaButtonTaped(sender: UIButton) {
        sender.enabled = false
        /// 清空验证码的输入框
        self.capchaTextField.text = ""
        self.capchaTextField.becomeFirstResponder()
        HDAPIService.sharedInstance.getCaptcha { (image, erro) in
            dispatch_async(dispatch_get_main_queue(), { 
                sender.enabled = true
                guard let img = image else {
                    HUD.flash(.LabeledError(title: "加载验证码失败", subtitle: "请检查网络或稍候再试"), delay: HUDShowRelay)
                    sender.setTitle("验证码", forState: UIControlState.Normal)
                    sender.setBackgroundImage(nil, forState: .Normal)
                    sender.enabled = true
                    return
                }
                
                sender.setBackgroundImage(img, forState: .Normal)
                sender.setTitle("", forState: .Normal)
            })
        }
        
    }
    
    
    @IBAction func cancelLogin(sender: UIButton) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}